package com.wang.head.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wang.common.pojo.BasePojoEnum;
import com.wang.common.pojo.BaseQuery;
import com.wang.common.util.ConstatFinalUtil;
import com.wang.common.web.controller.BaseController;
import com.wang.sys.pojo.AtSysFiles;
import com.wang.sys.pojo.AtSysFilesEnum;
import com.wang.sys.pojo.AtSysFilesQuery;
import com.wang.sys.service.AtSysFilesService;
import com.wang.train.pojo.AtExamDesc;
import com.wang.train.pojo.AtExamDescQuery;
import com.wang.train.pojo.AtExamDetail;
import com.wang.train.pojo.AtExamDetailEnum;
import com.wang.train.pojo.AtExamDetailQuery;
import com.wang.train.pojo.AtExamScoreDesc;
import com.wang.train.pojo.AtExamScoreDescQuery;
import com.wang.train.pojo.AtExamScoreDetail;
import com.wang.train.pojo.AtPlanUsers;
import com.wang.train.pojo.AtPlanUsersEnum;
import com.wang.train.pojo.AtPlanUsersQuery;
import com.wang.train.pojo.AtVideoDoc;
import com.wang.train.pojo.AtVideoDocQuery;
import com.wang.train.service.AtAnsSelService;
import com.wang.train.service.AtAskService;
import com.wang.train.service.AtCateService;
import com.wang.train.service.AtConsultService;
import com.wang.train.service.AtExamDescService;
import com.wang.train.service.AtExamDetailService;
import com.wang.train.service.AtExamScoreDescService;
import com.wang.train.service.AtExamScoreDetailService;
import com.wang.train.service.AtOrganService;
import com.wang.train.service.AtPlanDescService;
import com.wang.train.service.AtPlanUsersService;
import com.wang.train.service.AtVideoDocService;
import com.wang.users.pojo.AtUsersDesc;
import com.wang.users.service.AtUsersDescService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 示例的Controller
 * @author ZjxMi
 */
@Controller
@RequestMapping("/head/train")
@Log4j2
public class TrainHeadController extends BaseController {
    @Autowired
    private AtCateService cateService;
    @Autowired
    private AtOrganService organService;
    @Autowired
    private AtConsultService consultService;
    @Autowired
    private AtVideoDocService videoDocService;
    @Autowired
    private AtAskService askService;
    @Autowired
    private AtAnsSelService ansSelService;
    @Autowired
    private AtExamDescService examDescService;
    @Autowired
    private AtExamDetailService examDetailService;
    @Autowired
    private AtPlanDescService planDescService;
    @Autowired
    private AtPlanUsersService planUsersService;
    @Autowired
    private AtExamScoreDescService examScoreDescService;
    @Autowired
    private AtExamScoreDetailService examScoreDetailService;
    @Autowired
    private AtUsersDescService usersDescService;
    @Autowired
    private AtSysFilesService filesService;

    /**
     * 培训用户查询多条
     *
     * @return
     */
    @RequestMapping("/planUsersList")
    public String planUsersList(AtPlanUsersQuery paramQuery, Model model, HttpServletRequest request) {
        log.info("==培训用户列表==");
        AtUsersDesc usersDescSess = (AtUsersDesc) this.findObjFromSession(request, BasePojoEnum.SESS_USERS);
        /* 分页对象 */
        IPage<AtPlanUsers> paramPage = null;
        try {
            paramPage = new Page<>(paramQuery.getCurrent(), paramQuery.getSize());
        } catch (Exception e) {
            paramPage = new Page<>(1, 20);
        }
        /* 时间处理 */
        if (StringUtils.isNotEmpty(paramQuery.getStDate())) {
            paramQuery.setPubTimeSt(this.dateUtil.strToDateTime(paramQuery.getStDate()));
        }
        paramQuery.addLike();

        /* 增加条件 */
        AtPlanUsers entity = paramQuery.getEntity();
        entity.setUsersId(usersDescSess.getId());

        /* 查询对象 */
        List<AtPlanUsers> dataList = this.planUsersService.findList(paramPage, paramQuery);
        paramQuery.removeLike();
        /* 列表数据 */
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_DATALIST, dataList);
        /* 分页数据 */
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_PAGEINFOUTIL, paramPage);
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_PARAMQUERY, paramQuery);
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_ENUMSONE, new AtPlanUsers());
        /* 查询数据 */
        return "head/train/planUsersList";
    }

    /**
     * 培训用户打开更新页面
     * 更新和详情是同一个页面;
     *
     * @return
     */
    @RequestMapping("/planUsersUpdate")
    public String planUsersUpdate(AtPlanUsersQuery paramQuery, Model model) {
        log.info("==培训用户更新==");
        /* 根据id查询 */
        AtPlanUsers one = this.planUsersService.findOne(paramQuery);
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_ONE, one);
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_PARAMQUERY, paramQuery);
        if (BaseQuery.FINAL_OPER_UPDATE.equalsIgnoreCase(paramQuery.getOperType())) {
            /* 查询数据 */
            return "head/train/planUsersUpdate";
        }
        /* 查询数据 */
        return "head/train/planUsersInfo";
    }

    /**
     * 培训用户打开更新页面
     * 更新和详情是同一个页面;
     *
     * @return
     */
    @RequestMapping("/planUsersUpdateSubmit")
    public String planUsersUpdateSubmit(AtPlanUsersQuery paramQuery, Model model) {
        log.info("==培训用户更新提交==");
        AtPlanUsers entity = paramQuery.getEntity();
        if (StringUtils.isNotEmpty(paramQuery.getPubTime())) {
            entity.setPubTime(this.dateUtil.strToDateTime(paramQuery.getPubTime()));
        }
        /* 根据id查询 */
        boolean dbFlag = this.planUsersService.updateById(entity);
        JSONObject resultJson = this.proccedResponseJson(dbFlag);
        model.addAttribute(ConstatFinalUtil.FINAL_RESPONSE, resultJson);
        /* 查询数据 */
        return this.planUsersUpdate(paramQuery, model);
    }

    /**
     * 批量操作
     * 更新和详情是同一个页面;
     *
     * @return
     */
    @RequestMapping(value = "/planUsersBatch", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String planUsersBatch(AtPlanUsersQuery paramQuery, Model model) {
        log.info("==培训用户批量提交==");
        String operType = paramQuery.getOperType();
        String[] ids = paramQuery.getIds();
        String info = ConstatFinalUtil.FINAL_OPER_SUCCESS;
        int totalCount = 0;
        int succedCount = 0;
        int failedCount = 0;
        if (StringUtils.isNotEmpty(operType)) {
            if (Objects.nonNull(ids) && ids.length > 0) {
                totalCount = ids.length;
                for (String idTemp : ids) {
                    try {
                        AtPlanUsersQuery paramQueryTemp = new AtPlanUsersQuery();
                        AtPlanUsers entity = paramQueryTemp.getEntity();
                        entity.setId(idTemp);
                        /* 根据id查询每一个 记录对象 */
                        AtPlanUsers dataDbResult = this.planUsersService.findOne(paramQueryTemp);
                        if (dataDbResult != null) {
                            boolean dbFlag = false;
                            if (BasePojoEnum.OPERTYPE_UPDATESTATUS.getCode().equalsIgnoreCase(operType)) {
                                /* 批量修改状态 */
                                dataDbResult.setStatus(paramQuery.getEntity().getStatus());
                                dbFlag = this.planUsersService.updateById(dataDbResult);
                            }
                            if (dbFlag) {
                                succedCount ++;
                            } else {
                                failedCount ++;
                            }
                        }
                    } catch (Exception e) {
                        log.error("批量操作失败了,id:{}", idTemp, e);
                        failedCount ++;
                    }
                }
            } else {
                /* 未选择类型,ids */
                info = "ids为空";
            }
        } else {
            /* 操作类型未选择 */
            info = "操作类型未选择";
        }

        String messInfo = "批量操作日志:提示信息:${info}, 总条数:${totalCount},成功条数:${succedCount},失败条数:${failedCount}";
        Map<String,String> paramsMap = new HashMap<>(1);
        paramsMap.put("info", info);
        paramsMap.put("totalCount", String.valueOf(totalCount));
        paramsMap.put("succedCount", String.valueOf(succedCount));
        paramsMap.put("failedCount", String.valueOf(failedCount));
        messInfo = this.regexUtil.replaceOperator(messInfo, paramsMap);

        paramsMap = new HashMap<>(1);
        paramsMap.put(ConstatFinalUtil.FINAL_CONFIG_INFO_SUCCESS_PARAM1, messInfo);
        /* 查询数据 */
        JSONObject resultJson = this.proccedResponseJson(ConstatFinalUtil.FINAL_OPER_SUCCESS.equalsIgnoreCase(info), paramsMap);
        log.info("==结果:{}==", resultJson);
        return resultJson.toJSONString();
    }

    /**
     * 视频文档打开页面
     * @return
     */
    @RequestMapping("/videoDocUpdate")
    public String videoDocUpdate(AtVideoDocQuery paramQuery, Model model) {
        log.info("==视频文档更新==");
        /* 根据id查询 */
        AtVideoDoc one = this.videoDocService.findOne(paramQuery);
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_ONE, one);
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_PARAMQUERY, paramQuery);
        /* 查询视频列表 */
        AtSysFilesQuery filesQuery = new AtSysFilesQuery();
        AtSysFiles fileEntity = filesQuery.getEntity();
        fileEntity.setRelaId(one.getId());
        fileEntity.setRelaType(AtSysFilesEnum.RELATYPE_SYS.getCode());
        fileEntity.setStatus(BasePojoEnum.STATUS_ENABLE.getCode());
        fileEntity.setDelFlag(BasePojoEnum.DELFLAG_NO.getCode());
        List<AtSysFiles> fileList = this.filesService.findList(null,filesQuery);
        model.addAttribute("fileList", fileList);
        /* 查询数据 */
        return "head/train/videoDocInfo";
    }

    /**
     * 试新概要
     * @return
     */
    @RequestMapping("/examDescUpdate")
    public String examDescUpdate(AtExamDescQuery paramQuery, Model model) {
        log.info("==试新概要更新==");
        /* 根据id查询 */
        AtExamDesc one = this.examDescService.findOne(paramQuery);
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_ONE, one);
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_PARAMQUERY, paramQuery);

        /* 查询试卷列表,单选 */
        AtExamDetailQuery examDetailQuery = new AtExamDetailQuery();
        AtExamDetail examDetailEntity = examDetailQuery.getEntity();
        examDetailEntity.setExamId(one.getId());
        examDetailEntity.setAskType(AtExamDetailEnum.ASKTYPE_DANXT.getCode());
        examDetailEntity.setStatus(BasePojoEnum.STATUS_ENABLE.getCode());
        examDetailEntity.setDelFlag(BasePojoEnum.DELFLAG_NO.getCode());
        List<AtExamDetail> singleList = this.examDetailService.findList(null, examDetailQuery);
        model.addAttribute("singleList", singleList);

        /* 查询试卷列表,多选 */
        examDetailQuery = new AtExamDetailQuery();
        examDetailEntity = examDetailQuery.getEntity();
        examDetailEntity.setExamId(one.getId());
        examDetailEntity.setAskType(AtExamDetailEnum.ASKTYPE_DUOXT.getCode());
        examDetailEntity.setStatus(BasePojoEnum.STATUS_ENABLE.getCode());
        examDetailEntity.setDelFlag(BasePojoEnum.DELFLAG_NO.getCode());
        List<AtExamDetail> multiList = this.examDetailService.findList(null, examDetailQuery);
        model.addAttribute("multiList", multiList);

        /* 查询试卷列表,判断 */
        examDetailQuery = new AtExamDetailQuery();
        examDetailEntity = examDetailQuery.getEntity();
        examDetailEntity.setExamId(one.getId());
        examDetailEntity.setAskType(AtExamDetailEnum.ASKTYPE_PDT.getCode());
        examDetailEntity.setStatus(BasePojoEnum.STATUS_ENABLE.getCode());
        examDetailEntity.setDelFlag(BasePojoEnum.DELFLAG_NO.getCode());
        List<AtExamDetail> pdtList = this.examDetailService.findList(null, examDetailQuery);
        model.addAttribute("pdtList", pdtList);

        if (BaseQuery.FINAL_OPER_UPDATE.equalsIgnoreCase(paramQuery.getOperType())) {
            /* 更新,即提交试卷 */
            return "head/train/examDescUpdate";
        }
        /* 查询数据 */
        return "head/train/examDescInfo";
    }

    /**
     * 成绩概要查询多条
     *
     * @return
     */
    @RequestMapping("/examScoreDescList")
    public String examScoreDescList(AtExamScoreDescQuery paramQuery, Model model, HttpServletRequest request) {
        log.info("==成绩概要列表==");
        AtUsersDesc usersDescSess = (AtUsersDesc) this.findObjFromSession(request, BasePojoEnum.SESS_USERS);
        /* 分页对象 */
        IPage<AtExamScoreDesc> paramPage = null;
        try {
            paramPage = new Page<>(paramQuery.getCurrent(), paramQuery.getSize());
        } catch (Exception e) {
            paramPage = new Page<>(1, 20);
        }
        /* 时间处理 */
        if (StringUtils.isNotEmpty(paramQuery.getStDate())) {
            paramQuery.setPubTimeSt(this.dateUtil.strToDateTime(paramQuery.getStDate()));
        }
        paramQuery.addLike();

        /* 增加条件 */
        AtExamScoreDesc entity = paramQuery.getEntity();
        entity.setUsersId(usersDescSess.getId());

        /* 查询对象 */
        List<AtExamScoreDesc> dataList = this.examScoreDescService.findList(paramPage, paramQuery);
        paramQuery.removeLike();
        /* 列表数据 */
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_DATALIST, dataList);
        /* 分页数据 */
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_PAGEINFOUTIL, paramPage);
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_PARAMQUERY, paramQuery);
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_ENUMSONE, new AtExamScoreDesc());
        /* 查询数据 */
        return "head/train/examScoreDescList";
    }

    /**
     * 成绩概要打开添加页面
     * 更新和详情是同一个页面;
     *
     * @return
     */
    @RequestMapping("/examScoreDescInsert")
    public String examScoreDescInsert(AtExamScoreDescQuery paramQuery, Model model, HttpServletRequest request) {
        log.info("==成绩概要添加==");
        AtUsersDesc usersSess = (AtUsersDesc) this.findObjFromSession(request, BasePojoEnum.SESS_USERS);
        AtExamScoreDesc entity = paramQuery.getEntity();
        if (StringUtils.isEmpty(entity.getUsersId())) {
            /* 添加 */
            entity.setUsersId(usersSess.getId());
            entity.setOrganId(usersSess.getOrganId());
        }
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_ONE, entity);
        /* 查询数据 */
        return "head/train/examScoreDescInsert";
    }

    /**
     * 成绩概要打开更新页面
     * 更新和详情是同一个页面;
     * <pre>
     *     思路:
     *         根据试卷id查询试卷信息
     *         插入试卷信息和明细信息
     *         根据试卷id查询试卷明细和答案信息
     * </pre>
     * @return
     */
    @RequestMapping("/examScoreDescInsertSubmit")
    public String examScoreDescInsertSubmit(AtExamScoreDescQuery paramQuery, Model model, HttpServletRequest request) {
        log.info("==成绩概要添加提交==");
        AtUsersDesc usersSess = (AtUsersDesc) this.findObjFromSession(request, BasePojoEnum.SESS_USERS);
        AtExamScoreDesc entity = paramQuery.getEntity();

        /* 查询试卷信息 */
        AtExamDescQuery examDescQuery = new AtExamDescQuery();
        AtExamDesc examDescEntity = examDescQuery.getEntity();
        examDescEntity.setId(entity.getExamId());
        AtExamDesc examDesc = this.examDescService.findOne(examDescQuery);

        List<AtExamScoreDetail> examScoreDetailList = entity.getScoreDetailList();
        /* 获取所有的参数 */
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Iterator iterator = parameterMap.entrySet().iterator(); iterator.hasNext(); ) {
            Map.Entry<String, String[]> me = (Map.Entry<String, String[]>) iterator.next();
            String key = me.getKey();
            String[] values = me.getValue();

            if (key.startsWith("askId_")) {
                AtExamScoreDetail examScoreDetail = new AtExamScoreDetail();

                /* 是多选择的问题;单选,多选 */
                String[] keys = key.split("_");
                /* 问题id;askId */
                String askId = keys[1];
                /* 选项的值;会有多选 */
                String val = values[0];

                StringBuffer allValuesSb = new StringBuffer();
                for (int i = 0; i < values.length; i++) {
                    String tempStr = values[i];
                    allValuesSb.append(tempStr + ",");
                }
                examScoreDetail.setAskId(askId);
                examScoreDetail.setAnswer(allValuesSb.toString());

                /* 添加到集合中 */
                examScoreDetailList.add(examScoreDetail);
            }
        }

        /* 为属性赋值 */
        entity.setOrganId(examDesc.getOrganId());
        entity.setUsersId(usersSess.getId());

        /* 为对象赋值 */
        entity.setPubTime(new Date());
        boolean dbFlag = this.examScoreDescService.save(entity);

        /* 更新计划状态 */
        String planUsersId = request.getParameter("planUsersId");
        if (StringUtils.isNotEmpty(planUsersId)) {
            AtPlanUsersQuery planUsersQuery = new AtPlanUsersQuery();
            AtPlanUsers planUsersEntity = planUsersQuery.getEntity();
            planUsersEntity.setId(planUsersId);
            AtPlanUsers planUsersDb = this.planUsersService.findOne(planUsersQuery);
            if (Objects.nonNull(planUsersDb)) {
                planUsersDb.setStatus(AtPlanUsersEnum.STATUSNEW_FINIASH.getCode());
                this.planUsersService.updateById(planUsersDb);
            }
        }

        JSONObject resultJson = this.proccedResponseJson(dbFlag);
        model.addAttribute(ConstatFinalUtil.FINAL_RESPONSE, resultJson);
        /* 查询数据 */
        return "redirect:/head/train/examScoreDescUpdate?entity.id=" + entity.getId();
    }

    /**
     * 成绩概要打开更新页面
     * 更新和详情是同一个页面;
     *
     * @return
     */
    @RequestMapping("/examScoreDescUpdate")
    public String examScoreDescUpdate(HttpServletRequest request, AtExamScoreDescQuery paramQuery, Model model) {
        log.info("==成绩概要更新==");
        AtUsersDesc usersSess = (AtUsersDesc) this.findObjFromSession(request, BasePojoEnum.SESS_USERS);
        AtExamScoreDesc entity = paramQuery.getEntity();
        /* 根据根据,用户id和成绩id一块查询 */
        AtExamScoreDescQuery examScoreDescQuery = new AtExamScoreDescQuery();
        AtExamScoreDesc examScoreDescEntity = examScoreDescQuery.getEntity();
        examScoreDescEntity.setUsersId(usersSess.getId());
        examScoreDescEntity.setExamId(entity.getExamId());
        List<AtExamScoreDesc> scoreDescList = this.examScoreDescService.findList(null, examScoreDescQuery);
        AtExamScoreDesc one = null;
        if (!scoreDescList.isEmpty()) {
            one = scoreDescList.get(0);
            examScoreDescQuery = new AtExamScoreDescQuery();
            examScoreDescEntity = examScoreDescQuery.getEntity();
            examScoreDescEntity.setId(one.getId());
            one = this.examScoreDescService.findOne(examScoreDescQuery);
        }
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_ONE, one);
        model.addAttribute(ConstatFinalUtil.FINAL_CODE_PARAMQUERY, paramQuery);
        if (BaseQuery.FINAL_OPER_UPDATE.equalsIgnoreCase(paramQuery.getOperType())) {
            /* 查询数据 */
            return "head/train/examScoreDescUpdate";
        }
        /* 查询数据 */
        return "head/train/examScoreDescInfo";
    }

    /**
     * 成绩概要打开更新页面
     * 更新和详情是同一个页面;
     *
     * @return
     */
    @RequestMapping("/examScoreDescUpdateSubmit")
    public String examScoreDescUpdateSubmit(HttpServletRequest request, AtExamScoreDescQuery paramQuery, Model model) {
        log.info("==成绩概要更新提交==");
        AtExamScoreDesc entity = paramQuery.getEntity();
        if (StringUtils.isNotEmpty(paramQuery.getPubTime())) {
            entity.setPubTime(this.dateUtil.strToDateTime(paramQuery.getPubTime()));
        }
        /* 根据id查询 */
        boolean dbFlag = this.examScoreDescService.updateById(entity);
        JSONObject resultJson = this.proccedResponseJson(dbFlag);
        model.addAttribute(ConstatFinalUtil.FINAL_RESPONSE, resultJson);
        /* 查询数据 */
        return this.examScoreDescUpdate(request, paramQuery, model);
    }
}